import 'dart:async';
import 'dart:html' as html;

import '../all_websocket.dart' as imp;

///通用 Web WebSocket 接口
class WebSocket implements imp.WebSocket {
  html.WebSocket _soket;

  imp.OnMessage _onMessage;

  @override
  set onMessage(imp.OnMessage value) {
    _onMessage = value;
  }

  imp.OnClose _onClose;

  @override
  void set onClose(value) {
    _onClose = value;
  }

  imp.OnError _onError;

  @override
  void set onError(value) {
    _onError = value;
  }

  @override
  Future<imp.WebSocket> connect(String url, {Iterable<String> protocols}) async {
    var completer = Completer<imp.WebSocket>();
    try {
      _soket = html.WebSocket(url, protocols);
    } catch (e) {
      completer.completeError(e);
      _onError?.call(e);
    }
    _soket.onOpen.listen((event) {
      completer.complete(this);
    });
    _soket.onMessage.listen(_onDataListen);
    _soket.onError.listen(_onErrorListen);
    _soket.onClose.listen(_onDoneListen);

    return completer.future;
  }

  void _onDataListen(html.MessageEvent event) {
    _onMessage?.call(event.data);
  }

  void _onErrorListen(html.Event event) {
    _onError?.call(event.target);
  }

  void _onDoneListen(html.CloseEvent event) {
    _onClose?.call();
  }

  @override
  void close() {
    _soket?.close();
    _soket = null;
  }

  @override
  void add(data) {
    _soket?.send(data);
  }
}
